//
//  CWRichGestureLabel.m
//  CWChat
//
//  Created by 张小伟 on 2021/9/3.
//

#import "CWRichGestureLabel.h"
#import "DDRTHeader.h"

@interface CWRichGestureLabel ()

// 3个手势定义
@property(nonatomic,strong)UITapGestureRecognizer *tapGesture;
@property(nonatomic,strong)UILongPressGestureRecognizer *longPressGesture;
@property(nonatomic,strong)UIPanGestureRecognizer *panGesture;

@property(nonatomic,strong)NSDictionary *attributesDic;
@property(nonatomic,copy)GetClickBlock clickBlock;

@property(nonatomic,assign)BOOL isCancle;

@end

@implementation CWRichGestureLabel

-(id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}


-(id)creatRichGestureLabel:(NSString *)text andAttributes:(NSDictionary *)attributes andShow:(GetClickBlock)block {
    
    self.attributesDic = attributes;
    self.clickBlock = block;
    
    // 1.富文本文字的设置
    // 设置行距
    
    NSMutableParagraphStyle *muParagraph = [[NSMutableParagraphStyle alloc]init];
    muParagraph = [attributes objectForKey:NSParagraphStyleAttributeName];

    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    
    NSRange range = NSMakeRange(0, attrStr.length);
    // 设置字体大小
    UIFont *systemFont = [attributes objectForKey:NSFontAttributeName];
    [attrStr addAttribute:NSFontAttributeName value:systemFont range:range];
    // 设置字间距
    NSNumber *keyWordSpacing = [attributes objectForKey:NSKernAttributeName];
    [attrStr addAttribute:NSKernAttributeName value:keyWordSpacing range:range];
    
    // 设置段落样式
    [attrStr addAttribute:NSParagraphStyleAttributeName value:muParagraph range:range];
    
    self.attributedText = attrStr;
    
    
    // 获得一个字体的高
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:kTextFont]};

    CGSize singleSize = [CWRichGestureLabel getSingleWords:dic];
    
    CGSize size = [text boundingRectWithSize:self.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    // 加字间距后的行高
    CGFloat lineHeight = singleSize.height + muParagraph.lineSpacing;
    // 行数
    NSInteger lineCount = size.height/lineHeight;
    if (lineCount == 1 && fabs(size.height - lineHeight) <= 1.0 ) { // 只有一行的时候，刚好是1行文字加一行间距，所以设置lineCount为0，实际用下面的lineCount + 1的情形去展示
        // 这里的lineCount 为1时，其实有2种情形，一种是1行，1种是2行情况，为了更严谨一些，即把所有文字的行高和一个文字的行高相等时，即可，但为了避免文字计算有时会出现差距，则把2个值之差的绝对值控制在如1.0高度范围内，则为一行的情况来看待
        lineCount = 0;
    }
    // 其他情况为什么要 + 1 原因是因为，如果文字刚好2行时，其展示效果是2行文字，1行间距，那么除以一行文字和一行间距的和，值即为不到2，在NSInteger类型下，就为一行，所以无法展示出2行的内容，即应该把最后一行只有文字时不够一行文字和一行间距的和所除给入上去，所以要用lineCount + 1来进行处理
    DDLog(@"%ld",lineCount + 1);
        
    // 2.遮盖层的选择研究
    for (int index = 0; index < lineCount + 1; index ++) {
        UIBezierPath *path = [UIBezierPath bezierPath];
        CGFloat layerX = 0;
        CGFloat layerY = index * lineHeight;
        [path moveToPoint:CGPointMake(layerX, layerY)];
        [path addLineToPoint:CGPointMake(size.width, layerY)];
        [path addLineToPoint:CGPointMake(size.width, layerY + singleSize.height)];
        [path addLineToPoint:CGPointMake(layerX, layerY + singleSize.height)];

        [path closePath];
           
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.fillColor = [UIColor lightGrayColor].CGColor;
        layer.path = path.CGPath;
        
        [self.layer addSublayer:layer];
        
        UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(layerX, layerY, size.width, singleSize.height)];
        subView.backgroundColor = kThemeOrangeColor;
        subView.tag = index + 1;
        [self addSubview:subView];
    }
    
    // 3.手势添加的策略
    //创建手势添加到视图上
//    self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureClick:)];
//    [self addGestureRecognizer:self.tapGesture];
    
    //创建手势添加到视图上
    self.longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(gestureClick:)];
    self.longPressGesture.minimumPressDuration = 0.05;
    [self addGestureRecognizer:self.longPressGesture];

    //创建手势添加到视图上
    self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gestureClick:)];
    [self addGestureRecognizer:self.panGesture];
    
        
    return self;
}

/** 点击事件*/
-(void)gestureClick:(UIGestureRecognizer *)gesture {

    CGPoint touchPoint = [gesture locationInView:self];
   
    // 获得一个字体的高
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:kTextFont]};

    CGSize singleSize = [CWRichGestureLabel getSingleWords:dic];

    // 设置行距
    NSMutableParagraphStyle *muParagraph = [[NSMutableParagraphStyle alloc]init];
    muParagraph = [self.attributesDic objectForKey:NSParagraphStyleAttributeName];
    // 加字间距后的行高
    CGFloat lineHeight = singleSize.height + muParagraph.lineSpacing;
    // 点击的行数
    NSInteger lineCount = touchPoint.y/lineHeight;
    // 如果第一次点击，先将对应的第一层view删除的情况
    UIView *colorView = [self viewWithTag:lineCount + 1];
    if (colorView) {
        [colorView removeFromSuperview];
    }
    
    NSArray *layerArr = self.layer.sublayers;
    NSLog(@"lineCount = %ld state = %ld",lineCount,(long)gesture.state);
    if (lineCount < layerArr.count) { 
        //遍历当前视图上的子视图的presentationLayer 与点击的点是否有交集
//        NSLog(@"sublayers个数 = %ld",self.layer.sublayers.count);
        CALayer *clickLayer = layerArr[lineCount];

        for (CALayer *tempLayer in layerArr) {
            tempLayer.hidden = NO;
        }
// 不要点击手势，因为点击手势只有结束状态，用长按手势代替
//        if (gesture == self.tapGesture) {
//            if (gesture.state == UIGestureRecognizerStateEnded) {
                
//                clickLayer.hidden = YES;
//            }
//        }

        if (gesture.state != UIGestureRecognizerStateEnded) {
            NSLog(@"-----------------");
            clickLayer.hidden = YES;
        }

       

        if (self.clickBlock) {
            self.clickBlock(lineCount, YES);
        }
    }else {
        // 如果点击外侧把所有layer的隐藏状态设置为NO
        for (CALayer *tempLayer in layerArr) {
            tempLayer.hidden = NO;
        }
        if (self.clickBlock) {
            self.clickBlock(0, NO);
        }
    }
   
}

// 获得单个字的高和宽,重点是关注高，即关注一行字的高度
// 注意这里就不要传递行高来影响实际的单独字体高度，
+(CGSize)getSingleWords:(NSDictionary *)attributes;{
    CGSize singleSize = [@"A" boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return singleSize;
}


@end
